﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
using System.CodeDom;

namespace XChipTool
{
    public partial class XChip_CToCode : DevExpress.XtraEditors.XtraForm
    {
        public XChip_CToCode()
        {
            InitializeComponent();
        }

        private void buttonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
           
        }

        private void buttonEdit2_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
          
        }

        private void buttonEdit3_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            
        }

      

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "所有文件(*.h)|*.h";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {

                textEdit1.Text = sfd.FileName;

               
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "所有文件(*.c)|*.c";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                textEdit2.Text = sfd.FileName;
                //var list = File.ReadAllLines(sfd.FileName);
                //var pathname = Path.GetFileNameWithoutExtension(sfd.FileName);
                //var pathss = Path.GetDirectoryName(sfd.FileName);
                //var path = $"{pathss}\\B_{pathname}.cs";
                //using (StreamWriter writer = new StreamWriter(path))
                //{
                //    foreach (var item in list)
                //    {
                //        //if (item.Contains("WriteReg8(ISP0_BASE_ADDR+0x2695, 0x50)"))
                //        //{
                //        //    //var s = item.Replace("\t", "").Substring(0, 2);
                //        //}
                //        string itemT = item.Replace("\t", "");
                //        if (string.IsNullOrEmpty(itemT) || itemT.Contains("{") || itemT.Contains("}") || itemT.Length == 1 || itemT.Substring(0, 2) == "//")
                //        {
                //            writer.WriteLine(itemT);
                //            continue;
                //        }
                //        if (item.Contains("WriteReg8") && item.Contains("//"))
                //        {
                //            var indexT = itemT.IndexOf('/');
                //            var oneT = itemT.Substring(0, indexT);
                //            var twoT = itemT.Substring(indexT, itemT.Length - indexT);
                //            var str = $"{oneT.Replace("WriteReg8", "").Replace("(", "").Replace(")", "").Replace(";", "")},\"{twoT}\"";
                //            itemT = $"WriteReg8_note({str});";
                //        }
                //        writer.WriteLine(itemT);
                //    }
                //}
            }
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "所有文件(*.c)|*.c";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                textEdit3.Text = sfd.FileName;
                var list = File.ReadAllLines(sfd.FileName);
                var pathname = Path.GetFileNameWithoutExtension(sfd.FileName);
                var pathss = Path.GetDirectoryName(sfd.FileName);
                var path = $"{pathss}\\B_{pathname}.cs";

                using (StreamWriter writer = new StreamWriter(path))
                {
                    foreach (var item in list)
                    {
                        var itemT = item.Replace("\t", " ");

                        if (itemT.Contains("#include") ||
                            itemT.Contains("#define") ||
                            itemT.Contains("return") ||
                            itemT.Contains("printf") ||
                            itemT.Contains("fopen("))
                        {
                            continue;

                        }

                        if (itemT.Contains("main"))
                        {
                            itemT = $"void MainStart()";
                        }
                        else if (itemT.Contains("unsigned"))
                        {
                            itemT = itemT.Replace("unsigned", "").Replace("short", "uint");
                        }
                        writer.WriteLine(itemT);
                    }

                }
            }
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {


            //CtoCode cc = new CtoCode();
            //cc.GetMain();

            if (textEdit2.Text.Contains("请")|| string.IsNullOrEmpty(textEdit2.Text))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择文件！");
                return;
            }
            var list = File.ReadAllLines(textEdit2.Text);
            var pathname = Path.GetFileName(textEdit2.Text);
            var pathss = Path.GetDirectoryName(textEdit2.Text);
            var path = $"{pathss}\\B_{pathname}";
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in list)
                {
                    //if (item.Contains("WriteReg8(ISP0_BASE_ADDR+0x2695, 0x50)"))
                    //{
                    //    //var s = item.Replace("\t", "").Substring(0, 2);
                    //}
                    string itemT = item.Replace("\t", "");
                    if (string.IsNullOrEmpty(itemT) || itemT.Contains("{") || itemT.Contains("}") || itemT.Length == 1 || itemT.Substring(0, 2) == "//")
                    {
                        writer.WriteLine(itemT);
                        continue;
                    }
                    if (item.Contains("WriteReg8") && item.Contains("//"))
                    {
                        var indexT = itemT.IndexOf('/');
                        var oneT = itemT.Substring(0, indexT);
                        var twoT = itemT.Substring(indexT, itemT.Length - indexT);
                        var str = $"{oneT.Replace("WriteReg8", "").Replace("(", "").Replace(")", "").Replace(";", "")},\"{twoT}\"";
                        itemT = $"WriteReg8_note({str});";
                    }
                    writer.WriteLine(itemT);
                }
            }

            DevExpress.XtraEditors.XtraMessageBox.Show($"导出成功！ 文件路径：{path}");
        }

        /// <summary>
        /// 用来存储Header头文件
        /// </summary>
        List<object> listBoard { get; set; }
        /// <summary>
        /// 用来存储Misc文件内容
        /// </summary>
        List<object> listMisc { get; set; }
        /// <summary>
        /// 用来存储Main文件内容
        /// </summary>
        //List<object> listMain { get; set; }

        private void simpleButton5_Click(object sender, EventArgs e)
        {

            if (string.IsNullOrEmpty(textEdit1.Text)||textEdit1.Text.Contains("请"))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择.h文件");
                return;
            }
            if (string.IsNullOrEmpty(textEdit2.Text) || textEdit2.Text.Contains("请"))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择.c文件");
                return;
            }
            listBoard = new List<object>();
            listMisc = new List<object>();
            //listMain = new List<object>();
            var list = File.ReadAllLines(textEdit1.Text);
            var pathname = Path.GetFileNameWithoutExtension(textEdit1.Text);
            var pathss = Application.StartupPath + "\\Lib\\xc151_Bin";
            var path = $"{pathss}\\B_{pathname}.cs";

            #region .h文件解析
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in list)
                {
                    var itemT = item.Replace("\t", " ");
                    //if (item.Contains("I2C0_STATUS_ADDR"))
                    //{

                    //}
                    Regex regex = new Regex(@"(\w+\(\w+\))|(\w+\(\w+,\s*\w+\))");
                    if (string.IsNullOrEmpty(itemT) || itemT.Substring(0, 2) == "//" || regex.Match(itemT).Success)
                    {
                        continue;

                    }
                    if (itemT.Contains("#define"))
                    {
                        var dlist = itemT.Split(new char[] { ' ', '\t' }).Where(c => !string.IsNullOrEmpty(c)).ToList();
                        if (dlist.Count == 3)
                        {
                            var str = $"public const uint {dlist[1]} = {dlist[2]};";
                            listBoard.Add(str);
                            writer.WriteLine(str);
                        }
                        else if (dlist.Count > 3)
                        {
                            regex = new Regex(@"\(\w+ \+ 0x[0-9a-fA-F]+\)|\(0x[0-9a-fA-F]+\)");
                            MatchCollection matches = regex.Matches(item);
                            string str = string.Empty;
                            foreach (Match match in matches)
                            {
                                str += match.Value;
                            }
                            var str1 = $"public const uint {dlist[1]} = {str};";
                            listBoard.Add(str1);
                            writer.WriteLine(str1);
                        }
                    }
                }
            }
            listBoard.Add(" public  string setting = string.Empty;");

            listBoard.Add(" private List<string> mainList;");
            listBoard.Add(" public List<string> MainList{ get{if (null == mainList){mainList = new List<string>();} return mainList;} set{mainList = value;}}");
            #endregion

            list = File.ReadAllLines(textEdit2.Text);
            pathname = Path.GetFileNameWithoutExtension(textEdit2.Text);
            path = $"{pathss}\\B_{pathname}.cs";
            #region .c文件解析
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in list)
                {
                    //if (item.Contains("WriteReg8(ISP0_BASE_ADDR+0x2695, 0x50)"))
                    //{
                    //    //var s = item.Replace("\t", "").Substring(0, 2);
                    //}

                    string itemT = item.Replace("\t", "");
                    if (itemT.Contains("#include"))
                    {
                        continue;
                    }
                   
                    itemT = itemT.Replace("(void)", "()").Replace("void", "public void").Replace("unsigned char", "int").Replace("unsigned short", "uint").Replace("unsigned int", "long");
                    if (itemT.Contains("uint sensor_gain_addr[4]") || itemT.Contains("uint sensor_gain_mask[4]")
                       || itemT.Contains("uint sensor_exp_addr[4]") || itemT.Contains("uint sensor_exp_mask[4]")
                       || itemT.Contains("uint snr_blc_addr[4]"))
                    {
                        itemT = itemT.Replace("uint sensor_gain_addr[4]", "uint[] sensor_gain_addr").Replace("uint sensor_gain_mask[4]", "uint[] sensor_gain_mask").Replace("uint sensor_exp_addr[4]", "uint[] sensor_exp_addr").Replace("uint sensor_exp_mask[4]", "uint[] sensor_exp_mask").Replace("uint snr_blc_addr[4]", "uint[] snr_blc_addr");
                    }
                    if (itemT.Contains("uint HTS_addr[2]") || itemT.Contains("uint VTS_addr[2]"))
                    {
                        itemT = itemT.Replace("uint HTS_addr[2]", "uint[] HTS_addr").Replace("uint VTS_addr[2]", "uint[] VTS_addr");
                    }
                    if (string.IsNullOrEmpty(itemT) || itemT.Contains("{") || itemT.Contains("}") || itemT.Length == 1 || itemT.Substring(0, 2) == "//")
                    {
                        listMisc.Add(itemT);
                        writer.WriteLine(itemT);
                        continue;
                    }
                    if (!item.Contains("WriteReg8_note") &&item.Contains("WriteReg8") && item.Contains("//"))
                    {
                        var indexT = itemT.IndexOf('/');
                        var oneT = itemT.Substring(0, indexT);
                        var twoT = itemT.Substring(indexT, itemT.Length - indexT);
                        var str = $"{oneT.Replace("WriteReg8", "").Replace("(", "").Replace(")", "").Replace(";", "")},\"{twoT}\"";
                        itemT = $"WriteReg8_note({str});";
                    }
                    listMisc.Add(itemT);
                    writer.WriteLine(itemT);
                }
            }
            listMisc.Add(" public void ClearMainList() { mainList = new List<string>(); }");
            listMisc.Add(" public void fprintf(object obj, object obj1) { MainList.Add(obj1.ToString()); }");
            listMisc.Add(" public void WriteReg8_note(object obj, object obj1, object obj2) { MainList.Add(\"0x\"+Convert.ToUInt32( obj.ToString()).ToString(\"X2\") + \", 0x\" + Convert.ToUInt32( obj1.ToString()).ToString(\"X2\") + \", \" + obj2); }");
            listMisc.Add(" public void WriteReg8(object obj, object obj1) {  MainList.Add(\"0x\" + Convert.ToUInt32(obj.ToString()).ToString(\"X2\") + \", 0x\" + Convert.ToUInt32(obj1.ToString()).ToString(\"X2\") + \", \");  }");
            //listMisc.Add(" public void GetMain(){ MainStart(); File.WriteAllLines(\"C:\\\\Users\\\\Administrator\\\\Desktop\\\\123456.txt\", MainList.ToArray()); }");
            #endregion


            //list = File.ReadAllLines(textEdit3.Text);
            // pathname = Path.GetFileNameWithoutExtension(textEdit3.Text);
            // path = $"{pathss}\\B_{pathname}.cs";

            #region .c main 文件解析
            //using (StreamWriter writer = new StreamWriter(path))
            //{
            //    foreach (var item in list)
            //    {
            //        var itemT = item.Replace("\t", " ");

            //        if (itemT.Contains("#include") ||
            //            itemT.Contains("#define") ||
            //            itemT.Contains("return") ||
            //            itemT.Contains("printf") ||
            //            itemT.Contains("fopen("))
            //        {
            //            continue;

            //        }

            //        if (itemT.Contains("main"))
            //        {
            //            itemT = $"public void MainStart()";
            //        }
            //        else if (itemT.Contains("unsigned"))
            //        {
            //            itemT = itemT.Replace("unsigned short", "uint");
            //        }
            //        listMain.Add(itemT);
            //        writer.WriteLine(itemT);
            //    }

            //}

            #endregion

            //path = $"{pathss}\\B_mainStart.cs";

            StringBuilder sb = new StringBuilder();
            
            sb.AppendLine("using System;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.IO;");
            sb.Append(Environment.NewLine);
            sb.Append("namespace XChipTool");
            sb.Append(Environment.NewLine);
            sb.Append("{");
            sb.Append(Environment.NewLine);
            sb.Append("    public class CtoCode");
            sb.Append(Environment.NewLine);
            sb.Append("    {");
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in listBoard)
                {
                    sb.Append(Environment.NewLine);
                    sb.Append(item);
                    sb.Append(Environment.NewLine);
                    writer.WriteLine(item);
                }
                sb.Append(Environment.NewLine);
                foreach (var item in listMisc)
                {
                    sb.Append(Environment.NewLine);
                    sb.Append(item);
                    sb.Append(Environment.NewLine);
                    writer.WriteLine(item);
                }
                sb.Append(Environment.NewLine);
                //sb.Append(Environment.NewLine);
                //foreach (var item in listMain)
                //{
                //    sb.Append(Environment.NewLine);
                //    sb.Append(item);
                //    sb.Append(Environment.NewLine);
                //    writer.WriteLine(item);
                //}
                //sb.Append(Environment.NewLine);
            }
            sb.Append(Environment.NewLine);
            sb.Append("    }");
            sb.Append(Environment.NewLine);
            sb.Append("}");
            path = $"{pathss}\\CheckFilesCtoCodeLib.cs";
            File.WriteAllText(path,sb.ToString());
            

            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory = false;
            parameters.GenerateInMemory = false;
            parameters.OutputAssembly = "CtoCodeLib.dll";
            parameters.OutputAssembly = Application.StartupPath + "\\" + "CtoCodeLib.dll";
            parameters.ReferencedAssemblies.Add("System.dll");
            CompilerResults results = provider.CompileAssemblyFromSource(parameters, sb.ToString());

            
            if (results.Errors.HasErrors)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"编译失败！请检查语法问题！路径：{path}");
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"编译完成 路径:{ parameters.OutputAssembly}");
                // 通过反射，调用实例
                //Assembly objAssembly = results.CompiledAssembly;
                //var objCreate = objAssembly.CreateInstance("XChipTool.CtoCode");
                //MethodInfo method = objCreate.GetType().GetMethod("GetMain");
                //var methods = objCreate.GetType().GetMembers(BindingFlags.Public | BindingFlags.Static);
                //PropertyInfo[] properties = objCreate.GetType().GetProperties();
                //FieldInfo[] fields = objCreate.GetType().GetFields();
                //PropertyInfo property = objCreate.GetType().GetProperty("MainList");

                //method.Invoke(objCreate, null);
                //object value = property.GetValue(objCreate, null);
                //List<string> mainList = (List<string>)value;

            }

           
        }

        private void simpleButton10_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "所有文件(*.h)|*.h";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                textEdit6.Text = sfd.FileName;
            }
        }

        private void simpleButton9_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "所有文件(*.c)|*.c";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                textEdit5.Text = sfd.FileName;
            }
        }

        private void simpleButton8_Click(object sender, EventArgs e)
        {
            OpenFileDialog sfd = new OpenFileDialog();
            //设置文件类型 
            sfd.Filter = "所有文件(*.c)|*.c";
            //设置默认文件类型显示顺序 
            sfd.FilterIndex = 1;
            //保存对话框是否记忆上次打开的目录 
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                textEdit4.Text = sfd.FileName;
                var list = File.ReadAllLines(sfd.FileName);
                var pathname = Path.GetFileNameWithoutExtension(sfd.FileName);
                var pathss = Path.GetDirectoryName(sfd.FileName);
                var path = $"{pathss}\\B_{pathname}.cs";

                using (StreamWriter writer = new StreamWriter(path))
                {
                    foreach (var item in list)
                    {
                        var itemT = item.Replace("\t", " ");

                        if (itemT.Contains("#include") ||
                            itemT.Contains("#define") ||
                            itemT.Contains("return") ||
                            itemT.Contains("printf") ||
                            itemT.Contains("fopen("))
                        {
                            continue;

                        }

                        if (itemT.Contains("main"))
                        {
                            itemT = $"void MainStart()";
                        }
                        else if (itemT.Contains("unsigned"))
                        {
                            itemT = itemT.Replace("unsigned", "").Replace("short", "uint");
                        }
                        writer.WriteLine(itemT);
                    }

                }
            }
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            listBoard = new List<object>();
            listMisc = new List<object>();
            //listMain = new List<object>();
            var list = File.ReadAllLines(textEdit6.Text);
            var pathname = Path.GetFileNameWithoutExtension(textEdit6.Text);
            var pathss = Application.StartupPath + "\\Lib\\xc151_Bin";
            var path = $"{pathss}\\B_{pathname}.cs";

            #region .h文件解析
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in list)
                {
                    var itemT = item.Replace("\t", " ");
                    //if (item.Contains("I2C0_STATUS_ADDR"))
                    //{

                    //}
                    Regex regex = new Regex(@"(\w+\(\w+\))|(\w+\(\w+,\s*\w+\))");
                    if (string.IsNullOrEmpty(itemT) || itemT.Substring(0, 2) == "//" || regex.Match(itemT).Success)
                    {
                        continue;

                    }
                    if (itemT.Contains("#define"))
                    {
                        var dlist = itemT.Split(new char[] { ' ', '\t' }).Where(c => !string.IsNullOrEmpty(c)).ToList();
                        if (dlist.Count == 3)
                        {
                            var str = $"public const uint {dlist[1]} = {dlist[2]};";
                            listBoard.Add(str);
                            writer.WriteLine(str);
                        }
                        else if (dlist.Count > 3)
                        {
                            regex = new Regex(@"\(\w+ \+ 0x[0-9a-fA-F]+\)|\(0x[0-9a-fA-F]+\)");
                            MatchCollection matches = regex.Matches(item);
                            string str = string.Empty;
                            foreach (Match match in matches)
                            {
                                str += match.Value;
                            }
                            var str1 = $"public const uint {dlist[1]} = {str};";
                            listBoard.Add(str1);
                            writer.WriteLine(str1);
                        }
                    }
                }
            }
            listBoard.Add(" public  string setting = string.Empty;");

            listBoard.Add(" private List<string> mainList;");
            listBoard.Add(" public List<string> MainList{ get{if (null == mainList){mainList = new List<string>();} return mainList;} set{mainList = value;}}");
            #endregion

            list = File.ReadAllLines(textEdit5.Text);
            pathname = Path.GetFileNameWithoutExtension(textEdit5.Text);
            path = $"{pathss}\\B_{pathname}.cs";
            #region .c文件解析
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in list)
                {
                    //if (item.Contains("WriteReg8(ISP0_BASE_ADDR+0x2695, 0x50)"))
                    //{
                    //    //var s = item.Replace("\t", "").Substring(0, 2);
                    //}

                    string itemT = item.Replace("\t", "");
                    if (itemT.Contains("#include"))
                    {
                        continue;
                    }

                    itemT = itemT.Replace("(void)", "()").Replace("void", "public void").Replace("extern unsigned char", "int").Replace("unsigned char", "int").Replace("unsigned short", "int").Replace("unsigned int", "int").Replace("unsigned long", "int").Replace("unsigned", "int");
                    if (itemT .Contains("line_burst_num1"))
                    {

                    }
                    //string pattern = @"\(\w+\s*==\s*\d+\)|\w+\s?\?\s?(\w+)\s*:\s*(\w+)|(\w)+\s*:|\(\w+\s*\&\s*0x\w+\)\s?\?\s?(\w+)\s*:\s*(\w+)";
                    //string pattern = @"(\w+)\s*([?|:]\s*(\w+))";  \(\w+\s*==\s*\d+\)|\w+\s?\?\s?(\w+)\s*:\s*(\w+)|(\w)+\s*:
                    //\w +\s ?\?\s ? (\w +)\s *:\s * (\w +)
                    string pattern = @"\w+\s?\?\s?(\w+)\s*:\s*(\w+)";
                    Regex regex = new Regex(pattern);
                    Match match = regex.Match(itemT); // 将要匹配的字符串传入Match()函数
                    if (match.Success)
                    {
                        string condition = match.Groups["condition"].Value;


                        //Convert.ToBoolean()

                        //itemT = itemT.Replace(condition, $"Convert.ToBoolean({condition})");

                        pattern = @"\w+\s*?\?";
                        MatchCollection matches = Regex.Matches(match.Value, pattern);
                        foreach (Match mitem in matches)
                        {
                            itemT = itemT.Replace(mitem.Value, $"Convert.ToBoolean({mitem.Value.Replace("?","").Trim()})?");
                        }
                        pattern = @"\(\(\w+\s*==\s*\d+\)\s*&";
                        regex = new Regex(pattern);
                        match = regex.Match(itemT);
                        if (match.Success)
                        {
                            pattern = @"\(\w+\s*==\s*\d+\)";
                            matches = Regex.Matches(match.Value, pattern);
                            foreach (Match mitem in matches)
                            {
                                itemT = itemT.Replace($"({mitem.Value}", $" Convert.ToBoolean(Convert.ToUInt16({mitem.Value.Trim()})");
                            }
                        }

                        
                    }
                    pattern = @"\(\w+\s*\&\s*0x\w+\)\s?\?\s?(\w+)\s*:\s*(\w+)";
                    regex = new Regex(pattern);
                    match = regex.Match(itemT);
                    if (match.Success)
                    {
                        pattern = @"\(\w+\s*\&\s*0x\w+\)\s";
                        MatchCollection matches = Regex.Matches(match.Value, pattern);
                        foreach (Match mitem in matches)
                        {
                            itemT = itemT.Replace(mitem.Value, $"Convert.ToBoolean({mitem.Value.Trim()})");
                        }
                    }

                    pattern = @"(\w+)\((\w+)\s*&\s*0x(\d+)\)";
                    regex = new Regex(pattern);
                    match = regex.Match(itemT);
                    if (match.Success)
                    {
                      
                        string keyword = match.Groups[1].Value;
                        string part1 = match.Groups[2].Value;
                        string part2 = match.Groups[3].Value;


                       itemT = itemT.Replace(" ","").Replace($"{part1}&0x{part2}", $"Convert.ToBoolean({part1}&0x{part2})");
                    }

                    pattern = @"(\w+)\s*=\s*\(\s*(\w+\s*==\s*\d+)\)";
                    regex = new Regex(pattern);
                    match = regex.Match(itemT);
                    if (match.Success)
                    {

                        pattern = @"\(\w+\s*==\s*\d+\)";
                        MatchCollection matches = Regex.Matches(itemT, pattern);
                        foreach (Match mitem in matches)
                        {
                            itemT = itemT.Replace(mitem.Value, $"Convert.ToUInt16({mitem.Value.Trim()})");
                        }
                        


                        //itemT = itemT.Replace(" ", "").Replace($"{part1}&0x{part2}", $"Convert.ToBoolean({part1}&0x{part2})");
                    }
                    pattern = @"int\s*\w+\s*;";
                    regex = new Regex(pattern);
                    match = regex.Match(itemT);
                    if (match.Success)
                    {
                        itemT = itemT.Replace(";", "=0;");
                    }
                    pattern = @"if\s*\((\w+)\)|if\s*\((\w+)\)\{";
                    regex = new Regex(pattern);
                    match = regex.Match(itemT);
                    if (match.Success)
                    {
                        string capturedGroup = match.Groups[1].Value;
                        if (!string.IsNullOrEmpty(capturedGroup))
                        {
                            itemT = itemT.Replace(capturedGroup, $"Convert.ToBoolean({capturedGroup})");
                        }
                    }


                    if (itemT.Contains("uint sensor_gain_addr[4]") || itemT.Contains("uint sensor_gain_mask[4]")
                       || itemT.Contains("uint sensor_exp_addr[4]") || itemT.Contains("uint sensor_exp_mask[4]"))
                    {
                        itemT = itemT.Replace("[4]", "").Replace("uint", "uint[]");
                    }
                    if (string.IsNullOrEmpty(itemT) || itemT.Contains("{") || itemT.Contains("}") || itemT.Length == 1 || (itemT.Trim().Length >=2&& itemT.Trim().Substring(0, 2) == "//"))
                    {
                        listMisc.Add(itemT);
                        writer.WriteLine(itemT);
                        continue;
                    }
                    if (!item.Contains("WriteReg8_note") && item.Contains("WriteReg8") && item.Contains("//"))
                    {
                        var indexT = itemT.IndexOf('/');
                        var oneT = itemT.Substring(0, indexT);
                        var twoT = itemT.Substring(indexT, itemT.Length - indexT);
                        var str = $"{oneT.Replace("WriteReg8", "").Replace("(", "").Replace(")", "").Replace(";", "")},\"{twoT}\"";
                        itemT = $"WriteReg8_note({str});";
                    }
                    listMisc.Add(itemT);
                    writer.WriteLine(itemT);
                }
            }
            listMisc.Add(" public void ClearMainList() { mainList = new List<string>(); }");
            listMisc.Add(" public void fprintf(object obj, object obj1) { MainList.Add(obj1.ToString()); }");
            listMisc.Add(" public uint ReadReg8(uint obj) { MainList.Add(obj.ToString()); return obj;}");
            listMisc.Add(" public void WriteReg8_note(object obj, object obj1, object obj2) { MainList.Add(\"0x\"+Convert.ToUInt32( obj.ToString()).ToString(\"X2\") + \", 0x\" + Convert.ToUInt32( obj1.ToString()).ToString(\"X2\") + \", \" + obj2); }");
            listMisc.Add(" public void WriteReg8(object obj, object obj1) {  MainList.Add(\"0x\" + Convert.ToUInt32(obj.ToString()).ToString(\"X2\") + \", 0x\" + Convert.ToUInt32(obj1.ToString()).ToString(\"X2\") + \", \");  }");     
            listMisc.Add(" public void WriteReg32(object obj, object obj1) {  MainList.Add(\"0x\" + Convert.ToUInt32(obj.ToString()).ToString(\"X2\") + \", 0x\" + Convert.ToUInt32(obj1.ToString()).ToString(\"X2\") + \", \");  }");
            //listMisc.Add(" public void GetMain(){ MainStart(); File.WriteAllLines(\"C:\\\\Users\\\\Administrator\\\\Desktop\\\\123456.txt\", MainList.ToArray()); }");
            #endregion


            //list = File.ReadAllLines(textEdit3.Text);
            // pathname = Path.GetFileNameWithoutExtension(textEdit3.Text);
            // path = $"{pathss}\\B_{pathname}.cs";

            #region .c main 文件解析
            //using (StreamWriter writer = new StreamWriter(path))
            //{
            //    foreach (var item in list)
            //    {
            //        var itemT = item.Replace("\t", " ");

            //        if (itemT.Contains("#include") ||
            //            itemT.Contains("#define") ||
            //            itemT.Contains("return") ||
            //            itemT.Contains("printf") ||
            //            itemT.Contains("fopen("))
            //        {
            //            continue;

            //        }

            //        if (itemT.Contains("main"))
            //        {
            //            itemT = $"public void MainStart()";
            //        }
            //        else if (itemT.Contains("unsigned"))
            //        {
            //            itemT = itemT.Replace("unsigned short", "uint");
            //        }
            //        listMain.Add(itemT);
            //        writer.WriteLine(itemT);
            //    }

            //}

            #endregion

            //path = $"{pathss}\\B_mainStart.cs";

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("using System;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.IO;");
            sb.Append(Environment.NewLine);
            sb.Append("namespace XChipTool");
            sb.Append(Environment.NewLine);
            sb.Append("{");
            sb.Append(Environment.NewLine);
            sb.Append("    public class CtoCode");
            sb.Append(Environment.NewLine);
            sb.Append("    {");
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in listBoard)
                {
                    sb.Append(Environment.NewLine);
                    sb.Append(item);
                    sb.Append(Environment.NewLine);
                    writer.WriteLine(item);
                }
                sb.Append(Environment.NewLine);
                foreach (var item in listMisc)
                {
                    sb.Append(Environment.NewLine);
                    sb.Append(item);
                    sb.Append(Environment.NewLine);
                    writer.WriteLine(item);
                }
                sb.Append(Environment.NewLine);
                //sb.Append(Environment.NewLine);
                //foreach (var item in listMain)
                //{
                //    sb.Append(Environment.NewLine);
                //    sb.Append(item);
                //    sb.Append(Environment.NewLine);
                //    writer.WriteLine(item);
                //}
                //sb.Append(Environment.NewLine);
            }
            sb.Append(Environment.NewLine);
            sb.Append("    }");
            sb.Append(Environment.NewLine);
            sb.Append("}");
            path = $"{pathss}\\CheckFilesCtoCodeLib.cs";
            File.WriteAllText(path, sb.ToString());

        }

        private void simpleButton11_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(textEdit1.Text) || textEdit1.Text.Contains("请"))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择.h文件");
                return;
            }
            if (string.IsNullOrEmpty(textEdit2.Text) || textEdit2.Text.Contains("请"))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择.c文件");
                return;
            }
            listBoard = new List<object>();
            listMisc = new List<object>();
            //listMain = new List<object>();
            var list = File.ReadAllLines(textEdit1.Text);
            var pathname = Path.GetFileNameWithoutExtension(textEdit1.Text);
            var pathss = Application.StartupPath + "\\Lib\\xc151_Bin";
            var path = $"{pathss}\\B_{pathname}.cs";

            #region .h文件解析
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in list)
                {
                    var itemT = item.Replace("\t", " ");
                    //if (item.Contains("I2C0_STATUS_ADDR"))
                    //{

                    //}
                    Regex regex = new Regex(@"(\w+\(\w+\))|(\w+\(\w+,\s*\w+\))");
                    if (string.IsNullOrEmpty(itemT) || itemT.Substring(0, 2) == "//" || regex.Match(itemT).Success)
                    {
                        continue;

                    }
                    if (itemT.Contains("#define"))
                    {
                        var dlist = itemT.Split(new char[] { ' ', '\t' }).Where(c => !string.IsNullOrEmpty(c)).ToList();
                        if (dlist.Count == 3)
                        {
                            var str = $"public const uint {dlist[1]} = {dlist[2]};";
                            listBoard.Add(str);
                            writer.WriteLine(str);
                        }
                        else if (dlist.Count > 3)
                        {
                            regex = new Regex(@"\(\w+ \+ 0x[0-9a-fA-F]+\)|\(0x[0-9a-fA-F]+\)");
                            MatchCollection matches = regex.Matches(item);
                            string str = string.Empty;
                            foreach (Match match in matches)
                            {
                                str += match.Value;
                            }
                            var str1 = $"public const uint {dlist[1]} = {str};";
                            listBoard.Add(str1);
                            writer.WriteLine(str1);
                        }
                    }
                }
            }
            listBoard.Add(" public  string setting = string.Empty;");

            listBoard.Add(" private List<string> mainList;");
            listBoard.Add(" public List<string> MainList{ get{if (null == mainList){mainList = new List<string>();} return mainList;} set{mainList = value;}}");
            #endregion

            list = File.ReadAllLines(textEdit2.Text);
            pathname = Path.GetFileNameWithoutExtension(textEdit2.Text);
            path = $"{pathss}\\B_{pathname}.cs";
            #region .c文件解析
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in list)
                {
                    //if (item.Contains("WriteReg8(ISP0_BASE_ADDR+0x2695, 0x50)"))
                    //{
                    //    //var s = item.Replace("\t", "").Substring(0, 2);
                    //}

                    string itemT = item.Replace("\t", "");
                    if (itemT.Contains("#include"))
                    {
                        continue;
                    }

                    itemT = itemT.Replace("(void)", "()").Replace("void", "public void").Replace("unsigned char", "uint").Replace("unsigned short", "uint").Replace("unsigned int", "long");
                    if (itemT.Contains("uint snr_vts_addr_enable[4]") || itemT.Contains("uint snr_vts_addr[4]")
                       || itemT.Contains("uint Sensor_Mirror_Flip_Addr_Enable[8]") || itemT.Contains("uint Sensor_Mirror_Flip_Addr[8]")
                       || itemT.Contains("uint Mirror_Off_Flip_Off_Value[8]") || itemT.Contains("uint Mirror_On_Flip_Off_Value[8]")
                       || itemT.Contains("uint Mirror_Off_Flip_On_Value[8]") || itemT.Contains("uint Mirror_On_Flip_On_Value[8]")
                       )
                    {
                        itemT = itemT.Replace("uint snr_vts_addr_enable[4]", "uint[] snr_vts_addr_enable").Replace("uint snr_vts_addr[4]", "uint[] snr_vts_addr")
                            .Replace("uint Sensor_Mirror_Flip_Addr_Enable[8]", "uint[] Sensor_Mirror_Flip_Addr_Enable").Replace("uint Sensor_Mirror_Flip_Addr[8]", "uint[] Sensor_Mirror_Flip_Addr")
                            .Replace("uint Mirror_Off_Flip_Off_Value[8]", "uint[] Mirror_Off_Flip_Off_Value").Replace("uint Mirror_On_Flip_Off_Value[8]", "uint[] Mirror_On_Flip_Off_Value")
                            .Replace("uint Mirror_Off_Flip_On_Value[8]", "uint[] Mirror_Off_Flip_On_Value").Replace("uint Mirror_On_Flip_On_Value[8]", "uint[] Mirror_On_Flip_On_Value")
                            ;
                    }
                    //if (itemT.Contains("uint HTS_addr[2]") || itemT.Contains("uint VTS_addr[2]"))
                    //{
                    //    itemT = itemT.Replace("uint HTS_addr[2]", "uint[] HTS_addr").Replace("uint VTS_addr[2]", "uint[] VTS_addr");
                    //}
                    if (string.IsNullOrEmpty(itemT) || itemT.Contains("{") || itemT.Contains("}") || itemT.Length == 1 || itemT.Substring(0, 2) == "//")
                    {
                        listMisc.Add(itemT);
                        writer.WriteLine(itemT);
                        continue;
                    }
                    if (!item.Contains("WriteReg8_note") && item.Contains("WriteReg8") && item.Contains("//"))
                    {
                        var indexT = itemT.IndexOf('/');
                        var oneT = itemT.Substring(0, indexT);
                        var twoT = itemT.Substring(indexT, itemT.Length - indexT);
                        var str = $"{oneT.Replace("WriteReg8", "").Replace("(", "").Replace(")", "").Replace(";", "")},\"{twoT}\"";
                        itemT = $"WriteReg8_note({str});";
                    }
                    listMisc.Add(itemT);
                    writer.WriteLine(itemT);
                }
            }
            listMisc.Add(" public void ClearMainList() { mainList = new List<string>(); }");
            listMisc.Add(" public void fprintf(object obj, object obj1) { MainList.Add(obj1.ToString()); }");
            listMisc.Add(" public void WriteReg8_note(object obj, object obj1, object obj2) { MainList.Add(\"0x\"+Convert.ToUInt32( obj.ToString()).ToString(\"X2\") + \", 0x\" + Convert.ToUInt32( obj1.ToString()).ToString(\"X2\") + \", \" + obj2); }");
            listMisc.Add(" public void WriteReg8(object obj, object obj1) {  MainList.Add(\"0x\" + Convert.ToUInt32(obj.ToString()).ToString(\"X2\") + \", 0x\" + Convert.ToUInt32(obj1.ToString()).ToString(\"X2\") + \", \");  }");
            //listMisc.Add(" public void GetMain(){ MainStart(); File.WriteAllLines(\"C:\\\\Users\\\\Administrator\\\\Desktop\\\\123456.txt\", MainList.ToArray()); }");
            #endregion


            //list = File.ReadAllLines(textEdit3.Text);
            // pathname = Path.GetFileNameWithoutExtension(textEdit3.Text);
            // path = $"{pathss}\\B_{pathname}.cs";

            #region .c main 文件解析
            //using (StreamWriter writer = new StreamWriter(path))
            //{
            //    foreach (var item in list)
            //    {
            //        var itemT = item.Replace("\t", " ");

            //        if (itemT.Contains("#include") ||
            //            itemT.Contains("#define") ||
            //            itemT.Contains("return") ||
            //            itemT.Contains("printf") ||
            //            itemT.Contains("fopen("))
            //        {
            //            continue;

            //        }

            //        if (itemT.Contains("main"))
            //        {
            //            itemT = $"public void MainStart()";
            //        }
            //        else if (itemT.Contains("unsigned"))
            //        {
            //            itemT = itemT.Replace("unsigned short", "uint");
            //        }
            //        listMain.Add(itemT);
            //        writer.WriteLine(itemT);
            //    }

            //}

            #endregion

            //path = $"{pathss}\\B_mainStart.cs";

            StringBuilder sb = new StringBuilder();

            sb.AppendLine("using System;");
            sb.AppendLine("using System.Collections.Generic;");
            sb.AppendLine("using System.IO;");
            sb.Append(Environment.NewLine);
            sb.Append("namespace XChipTool");
            sb.Append(Environment.NewLine);
            sb.Append("{");
            sb.Append(Environment.NewLine);
            sb.Append("    public class FunctionCode");
            sb.Append(Environment.NewLine);
            sb.Append("    {");
            using (StreamWriter writer = new StreamWriter(path))
            {
                foreach (var item in listBoard)
                {
                    sb.Append(Environment.NewLine);
                    sb.Append(item);
                    sb.Append(Environment.NewLine);
                    writer.WriteLine(item);
                }
                sb.Append(Environment.NewLine);
                foreach (var item in listMisc)
                {
                    sb.Append(Environment.NewLine);
                    sb.Append(item);
                    sb.Append(Environment.NewLine);
                    writer.WriteLine(item);
                }
                sb.Append(Environment.NewLine);
                //sb.Append(Environment.NewLine);
                //foreach (var item in listMain)
                //{
                //    sb.Append(Environment.NewLine);
                //    sb.Append(item);
                //    sb.Append(Environment.NewLine);
                //    writer.WriteLine(item);
                //}
                //sb.Append(Environment.NewLine);
            }
            sb.Append(Environment.NewLine);
            sb.Append("    }");
            sb.Append(Environment.NewLine);
            sb.Append("}");
            path = $"{pathss}\\CheckFilesFunctionCodeLib.cs";
            File.WriteAllText(path, sb.ToString());


            CSharpCodeProvider provider = new CSharpCodeProvider();
            CompilerParameters parameters = new CompilerParameters();
            parameters.GenerateInMemory = false;
            parameters.GenerateInMemory = false;
            parameters.OutputAssembly = "FunctionCodeLib.dll";
            parameters.OutputAssembly = Application.StartupPath + "\\" + "FunctionCodeLib.dll";
            parameters.ReferencedAssemblies.Add("System.dll");
            CompilerResults results = provider.CompileAssemblyFromSource(parameters, sb.ToString());


            if (results.Errors.HasErrors)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"编译失败！请检查语法问题！路径：{path}");
            }
            else
            {
                DevExpress.XtraEditors.XtraMessageBox.Show($"编译完成 路径:{ parameters.OutputAssembly}");
                // 通过反射，调用实例
                //Assembly objAssembly = results.CompiledAssembly;
                //var objCreate = objAssembly.CreateInstance("XChipTool.CtoCode");
                //MethodInfo method = objCreate.GetType().GetMethod("GetMain");
                //var methods = objCreate.GetType().GetMembers(BindingFlags.Public | BindingFlags.Static);
                //PropertyInfo[] properties = objCreate.GetType().GetProperties();
                //FieldInfo[] fields = objCreate.GetType().GetFields();
                //PropertyInfo property = objCreate.GetType().GetProperty("MainList");

                //method.Invoke(objCreate, null);
                //object value = property.GetValue(objCreate, null);
                //List<string> mainList = (List<string>)value;

            }
        }
    }
}